package DD3;

public class deadlock1 {

	public static void main(String[] args) {

		StringBuffer s1 = new StringBuffer();
		StringBuffer s2 = new StringBuffer();

		new Thread() {
			public void run() {

				synchronized (s1) {

					s1.append("a");
					s2.append("1");
					// We use the sleep to increase THE CHANCES OF deadlock

					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					// When we comment out this paragraph we greatly reduce the chance of deadlock

					synchronized (s2) {
						s1.append("b");
						s2.append("2");

						System.out.println(s1);
						System.out.println(s2);
					}

				}

			}
		}.start();
		new Thread(new Runnable()
		{
			public void run() {
				synchronized (s2) {

					s1.append("c");
					s2.append("3");

					try {
						Thread.sleep(100);
					} catch (Exception e) {
						e.printStackTrace();
					}

					synchronized (s1) {
						s1.append("d");
						s2.append("4");

						System.out.println(s1);
						System.out.println(s2);
					}
				}
			}
		}).start();
	}

}
